﻿using Aliyun.OSS;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace VS2022ToGitee.WebApi.Controllers
{
    public class UploadController : BaseController
    {
        private readonly string _accessKeyId = "LTAI5tQwXWgTiTsB9SrSTDBr";
        private readonly string _accessKeySecret = "B0OheuPI7jgzXB0z4nlBoFSTYmaYTQ";
        private readonly string _endpoint = "https://oss-cn-shanghai-internal.aliyuncs.com"; 
        private readonly string _bucketName = "organization-digitizes";

        [HttpPost("upload-to-oss")]
        public async Task<IActionResult> UploadToOss([FromBody] FileUrlModel fileUrl)
        {
            if (string.IsNullOrEmpty(fileUrl.Url))
            {
                return BadRequest("URL is required.");
            }

            try
            {
                var client = new OssClient(_endpoint, _accessKeyId, _accessKeySecret);
                using var httpClient = new HttpClient();
                using var response = await httpClient.GetAsync(fileUrl.Url);
                if (!response.IsSuccessStatusCode)
                {
                    return StatusCode((int)response.StatusCode, "Failed to download the file.");
                }

                using var stream = await response.Content.ReadAsStreamAsync();
                var objectName = Path.GetFileName(new Uri(fileUrl.Url).LocalPath); // 获取文件名

                // 上传到OSS
                client.PutObject(_bucketName, objectName, stream);

                return Ok($"File uploaded successfully: {objectName}");
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"Error uploading file: {ex.Message}");
            }
        }
        public class FileUrlModel
        {
            public string? Url { get; set; }
        }
    }
}
